#coding=utf-8

from socket import *
from time import ctime
import traceback
import sys

host = ''
port = 12345
BUF_SIZE = 1024
addr = (host,port)

server = socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(addr)
server.listen(5)
print gethostname()
print gethostbyname(gethostname())

while True:
	print('waiting for connection.....')
	try:
		client_sock,client_addr = server.accept()
	except KeyboardInterrupt:
		print('keyboard exception')
		raise
	except:
		print('any exception')
		traceback.print_exc()
		sys.exit()
	print('...connected from:',client_addr)
	#client_sock.setblocking(0)
	
	try:
		while True:
			print('waiting for recv')
			data = client_sock.recv(BUF_SIZE)
			print 'rec data'
			if not data:
				print('null data')
				break
			print(data)
			client_sock.send('[%s] %s'%(ctime(),data))
	except Exception,e:
		print(str(e))
		print('continue listen...')
		continue

	client_sock.close()

server.close()



